<template>
    <div>
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="我的测评ID">
                <el-input v-model="queryInfo.id" placeholder="请输入我的测评ID" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getList">搜索</el-button>
                <el-button type="primary" @click="reset" style="margin-left: 30px;">重置</el-button>
            </el-form-item>
        </el-form>
        <div class="mb20">
            <el-button @click="toAdd" type="primary" icon="Plus" plain>新增</el-button>
            <!-- <el-button type="danger" icon="Delete" plain>删除</el-button> -->
        </div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed prop="id" label="我的测评ID" width="110" />
            <el-table-column type="selection" width="30" />
            <el-table-column prop="user.username" label="用户名" width="100" />
            <el-table-column prop="user.phone" label="手机号" width="110" />
            <el-table-column prop="user.name" label="姓名" width="100" />
            <el-table-column prop="heartMark.name" label="测评标题" width="100">
                <template #default="scope">
                    <el-button link type="primary" v-if="scope.row.heartMark.name != null"
                        @click="details(1, scope.row)">
                        <el-icon>
                            <Help />
                        </el-icon>
                        <span>详情</span>
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="heartMark.simplyIntroduce" label="测评简介" width="100">
                <template #default="scope">
                    <el-button link type="primary" v-if="scope.row.heartMark.simplyIntroduce != null"
                        @click="details(2, scope.row)">
                        <el-icon>
                            <Help />
                        </el-icon>
                        <span>详情</span>
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="heartMark.img" label="测评图片" width="135">
                <template #default="scope">
                    <el-image v-if="scope.row.heartMark.img" style="width: 100px; height: 100px"
                        :src="url + scope.row.heartMark.img" :fit="fit" />
                </template>
            </el-table-column>
            <el-table-column prop="heartMark.total" label="题目数量" width="100" />
            <el-table-column prop="testTime" label="测评时间" width="110" />
            <el-table-column fixed="right" label="操作" min-width="55">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="toEdit(scope.row)"
                        style="margin-left: 10px;">修改</el-button>
                    <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="demo-pagination-block" style="margin-left: 260px; margin-top: 15px;">
            <el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
                :page-sizes="[1, 2, 3, 4]" :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
    <!-- 添加，编辑弹框 -->
    <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="500">
        <el-form :model="myTest">
            <el-form-item label="用户ID" :label-width="formLabelWidth">
                <el-input v-model="myTest.userId" autocomplete="off" style="margin-left: 15px" />
            </el-form-item>
            <el-form-item label="测评ID" :label-width="formLabelWidth">
                <el-input v-model="myTest.testId" autocomplete="off" style="margin-left: 15px" />
            </el-form-item>
            <el-form-item label="心测ID" :label-width="formLabelWidth">
                <el-input v-model="myTest.heartMark.id" autocomplete="off" style="margin-left: 15px" />
            </el-form-item>
            <el-form-item label="测评标题" :label-width="formLabelWidth">
                <quill-editor v-model:value="myTest.heartMark.name" />
            </el-form-item>
            <el-form-item label="测评简介" :label-width="formLabelWidth">
                <quill-editor v-model:value="myTest.heartMark.simplyIntroduce" />
            </el-form-item>
            <el-form-item label="测评图片" :label-width="formLabelWidth">
                <el-upload v-model:file-list="fileList" class="avatar-uploader" list-type="picture-card"
                    action="http://localhost:80/file/upload" :on-success="handleAvatarSuccess">
                    <img v-if="myTest.heartMark.img" :src="myTest.heartMark.img" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="题目数量" :label-width="formLabelWidth">
                <el-input v-model="myTest.heartMark.total" autocomplete="off" />
            </el-form-item>
            <el-form-item label="测评时间" :label-width="formLabelWidth">
                <el-input v-model="myTest.testTime" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="saveOrUpdate">
                    {{ saveOrUpdateTitle }}
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="detailsVisible" :title="detailsInfor.heartMark.name != null ? '测评标题' : '测评简介'" width="1000"
        @close="clearInfor()">
        <quill-editor v-if="detailsInfor.heartMark.name != null" v-model:value="detailsInfor.heartMark.name" />
        <quill-editor v-if="detailsInfor.heartMark.simplyIntroduce != null"
            v-model:value="detailsInfor.heartMark.simplyIntroduce" />
    </el-dialog>
</template>
<style scoped>
.avatar-uploader .el-upload-list__item {
    border: none !important;
    /* 移除边框 */
    box-shadow: none !important;
    /* 移除阴影 */
}
</style>
<script setup>
import { ref,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import QuillEditor from '@/components/QuillEditor.vue';
const tableData = ref([]);
const total = ref(0);
const detailsVisible = ref(false);
function clearInfor() {
    detailsInfor.value.heartMark.name = null;
    detailsInfor.value.heartMark.simplyIntroduce = null;
}
const detailsInfor = ref({
    heartMark: {
        name: null,
        simplyIntroduce: null
    }
});
function details(n, row) {
    detailsVisible.value = true;
    if (n == 1) {
        detailsInfor.value.heartMark.name = row.heartMark.name;
    } else {
        detailsInfor.value.heartMark.simplyIntroduce = row.heartMark.simplyIntroduce;
    }


}
//定义图片路径
const url = ref('http://localhost:80/file/downLoad?fileName=')
// 定义一个方法当页面加载后立马执行的代码
onMounted(() => {
    getList();
})
//分页
const handleSizeChange = (val) => {
    queryInfo.value.pageNum = 1;
    queryInfo.value.pageSize = val;
    getList();
}
const handleCurrentChange = (val) => {
    queryInfo.value.pageNum = val;
    getList();
}
// 定义一个全局的查询参数变量
const queryInfo = ref({
    pageNum: 1,
    pageSize: 3,
    name: ''
})
//定义一个方法，来动态的调用后端接口，获取文章列表
const getList = () => {
    axios.get('/myTest/findAll', {
        params: queryInfo.value
    })
        .then(resp => {
            let result = resp.data;
            if (result.code == 1) {
                total.value = result.data.total;
                tableData.value = result.data.list.map(item => {
                    // 确保 heartMark 对象存在
                    if (!item.heartMark) {
                        item.heartMark = {
                            name: null,
                            simplyIntroduce: null,
                            img: null,
                            total: null
                        };
                    }
                    return item;
                });
            }
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}
//重置
const reset = () => {
    queryInfo.value = {
        pageNum: 1,
        pageSize: 3,
        name: ''
    }
    getList();
}
// 删除
const onDel = id => {
    ElMessageBox.confirm(
        '真的要删除吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 调用后端接口删除
            axios.delete('/myTest/delete/' + id)
                .then(resp => {
                    let result = resp.data;  // resp是promise对象，.data返回我们自己的标准R 
                    if (result.code == 1) {
                        // 重新获取列表
                        getList();
                        ElMessage({
                            message: '删除成功！',
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: '删除失败！',
                            type: 'warning',
                        })
                    }
                })
        })
        .catch(() => { })
}
// 修改或添加
const saveOrUpdateVisible = ref(false);
const myTest = ref({
    userId: '',
    testId: '',
    testTime: '',
    user: {
        username: '',
        phone: '',
        name: '',
    },
    heartMark: {
        id: '',
        name: '',
        simplyIntroduce: '',
        img: '',
        total: '',
    },

})
const saveOrUpdateTitle = ref('添加');
// 去添加的页面

const toAdd = row => {
    fileList.value = [];
    imageUrl.value = '';
    saveOrUpdateVisible.value = true;
    saveOrUpdateTitle.value = '添加';
    myTest.value = {
        userId: '',
        testId: '',
        testTime: '',
        user: {
            username: '',
            phone: '',
            name: '',
        },
        heartMark: {
            id: '',
            name: ' ',
            simplyIntroduce: ' ',
            img: '',
            total: '',
        },

    }
}
// 去修改的页面
const fileList = ref([]);
const imageUrl = ref('');
const toEdit = row => {
    saveOrUpdateVisible.value = true;
    saveOrUpdateTitle.value = '编辑';
    myTest.value = row;
    // 把图片的名称和路径放入到fileList中
    fileList.value = [{
        name: '0000',
        url: url.value + myTest.value.heartMark.img
    }];
}
//保存图片
const handleAvatarSuccess = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    myTest.value.heartMark.img = response.data;
}
// 取消修改或保存
const close = () => {
    saveOrUpdateVisible.value = false;
    // 请求图片展示
    imageUrl.value = '';
    fileList.value = [];
    myTest.value = {
        userId: '',
        testId: '',
        testTime: '',
        user: {
            username: '',
            phone: '',
            name: '',
        },
        heartMark: {
            id: '',
            name: '',
            simplyIntroduce: '',
            img: '',
            total: '',
        },

    }
}
// 保存或更新
const saveOrUpdate = () => {
    if (myTest.value.testId === myTest.value.heartMark.id) {
        fileList.value = [];
        saveOrUpdateVisible.value = false;
        if (saveOrUpdateTitle.value == '添加') {
            axios.post('/myTest/addMyTest', myTest.value)
                .then(resp => {
                    console.log('Add response:', resp.data);
                    let result = resp.data;
                    if (result.code == 1) {
                        // 重新获取列表
                        getList();
                        ElMessage({
                            message: '添加成功！',
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: '添加失败！',
                            type: 'warning',
                        })
                    }
                })
                .catch(error => {
                    console.error('Add request failed:', error);
                    ElMessage({
                        message: '添加请求失败！',
                        type: 'error',
                    })
                });
        } else {
            axios.put('/myTest/updateMyTest', myTest.value)
                .then(resp => {
                    console.log('Update response:', resp.data);
                    let result = resp.data;
                    if (result.code == 1) {
                        // 重新获取列表
                        getList();
                        ElMessage({
                            message: '修改成功！',
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: '修改失败！',
                            type: 'warning',
                        })
                    }
                })
                .catch(error => {
                    ElMessage({
                        message: '修改请求失败！',
                        type: 'error',
                    })
                });
        }
    } else {
        console.log('Test IDs are not equal, showing error message');
        ElMessage({
            message: '测评ID与心理测评ID不一致，请保持测评ID与心理测评ID一致！',
            type: 'error',
        });
        saveOrUpdateVisible.value = true; // 重新打开弹框
        return; // 阻止后续的保存或更新操作
    }
}
</script>
